package com.jdragon.common.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Jdragon
 * @email: 1061917196@qq.com
 * @Date: 2020.07.27 21:07
 * @Description:
 */
public class QuartzTemplate {

    private final static String DEFAULT = "default";

    private Scheduler scheduler;

    public QuartzTemplate(){
        try {
            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            this.scheduler = schedulerFactory.getScheduler();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public QuartzTemplate(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public void addJob(String cronExpress, Class<? extends Job> jobClass) {
        addJob(DEFAULT, DEFAULT, cronExpress, jobClass, new HashMap<>());
    }

    public void addJob(String jobName, String cronExpress, Class<? extends Job> jobClass) {
        addJob(jobName, DEFAULT, cronExpress, jobClass, new HashMap<>());
    }

    public void addJob(String jobName, String group, String cronExpress, Class<? extends Job> jobClass) {
        addJob(jobName, group, cronExpress, jobClass, new HashMap<>());
    }

    /**
     * 添加作业
     *
     * @param jobName     作业名称
     * @param cronExpress 时间表达式
     * @param jobClass    集成 job 类 的实现类
     * @param params      所需参数
     */
    public void addJob(String jobName, String group, String cronExpress, Class<? extends Job> jobClass, Map<String, Object> params) {
        try {
            //添加触发调度名称
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, group);
            //判断时间表达式是否有效
            if (!CronExpression.isValidExpression(cronExpress)) {
                throw new QuartzException("时间表达式格式错误: " + cronExpress);
            }
            //设置触发时间
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpress);
            //触发建立
            CronTrigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity(triggerKey)
                    .withSchedule(cronScheduleBuilder)
                    .build();

            //添加名称
            JobKey jobKey = JobKey.jobKey(jobName, group);
            //建立
            JobDetail jobDetail = JobBuilder.newJob(jobClass)
                    .withIdentity(jobKey)
                    .build();
            //传入调度的数据，在QuartzFactory中需要使用
            jobDetail.getJobDataMap().putAll(params);
            //调度作业
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            throw new QuartzException(e);
        }
    }
}
